/*
 * @copyright <a href='mailto:fxsen@foxmail.com'> <br/>
 * @date 2022/4/26 20:45 <br/>
 * @email <a href='mailto:fxsen@foxmail.com'>
 * @author fxsen
 */
package com.fxsen.commons.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.annotation.TableName;
import com.gitee.sunchenbin.mybatis.actable.annotation.TableComment;
import org.apache.commons.lang3.StringUtils;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.Objects;

/**
 * 通过实体类class生成代码dao和service
 * @author fxsen
 * @date 2022/4/26 20:45
 * @email <a href='mailto:fxsen@foxmail.com'>
 */
public class CodeUtils {
    public static void createDaoAndService(Class c,String project,String folder,String author) {
        //通过Class获取到当前Class的目录
        String path = Objects.requireNonNull(c.getClassLoader().getResource("")).getPath().replaceFirst("/","").
                replace("/target/classes/","").replace("/",File.separator);
        //如果为空就默认
        if (StringUtils.isBlank(folder)){
            //首字母小写
            folder = StrUtil.lowerFirst(c.getSimpleName());
        }
        String[] daoStr = new String[] {path,"src","main","java","com","fxsen",project,"core","models",folder,"mapper"};
        String daoDir = getString(daoStr, File.separator);
        createMapperClass(c, daoDir,project,folder,author);
        String[] serviceStr = new String[] {path,"src","main","java","com","fxsen",project,"core","models",folder,"service"};
        String serviceDir = getString(serviceStr, File.separator);
        createServiceClass(c, serviceDir,project,folder,author);
        String[] serviceImplStr = new String[] {path,"src","main","java","com","fxsen",project,"core","models",folder,"service", "impl"};
        String serviceImpDir = getString(serviceImplStr, File.separator);
        createServiceImplClass(c, serviceImpDir,project,folder,author);
    }
    /**
    * 创建Mapper类
    * @date 2022/4/26 20:55
    * @author fxsen <br/>
    * @email <a href='mailto:fxsen@foxmail.com'>
    **/
    private static void createMapperClass(Class model, String mapperDir,String project,String folder,String author) {
        try {
            String comment = getComment(model)+"数据持久层";
            String date = DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss");
            StringBuffer buf = new StringBuffer();
            String className = model.getSimpleName() + "Mapper";
            String str = "/*\n" +
                    " * @copyright "+author+" <br/>\n" +
                    " * @date "+ DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss") +" <br/>\n" +
                    " * @author fxsen\n" +
                    " */\n" +
                    "package com.fxsen."+project+".core.models."+folder+".mapper;\n" +
                    "import org.apache.ibatis.annotations.Mapper;\n" +
                    "import org.springframework.stereotype.Repository;\n" +
                    "import com.fxsen.commons.core.base.common.mapper.CommonMapper;\n" +
                    "import "+model.getName()+";\n" +
                    "/**\n" +
                    " * "+comment+"\n"+
                    " * @author "+author+"\n" +
                    " * @date "+ date +" \n" +
                    " */\n"+
                    "@Mapper\n" +
                    "@Repository\n" +
                    "public interface "+className+" extends CommonMapper<"+model.getSimpleName()+">{\n" +
                    "\n" +
                    "}\n" +
                    "";
            buf.append(str);
            File file = new File(mapperDir);
            if (!file .exists() && !file .isDirectory()){
                file.mkdirs();
            }
            File f = new File(mapperDir + model.getSimpleName() + "Mapper.java");
            if (!f.exists()) {
                f.createNewFile();
            }
            OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(f), StandardCharsets.UTF_8);
            BufferedWriter writer = new BufferedWriter(write);
            writer.write(buf.toString());
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
    * 创建Service
    * @date 2022/4/26 22:17
    * @author fxsen <br/>
    * @email <a href="mailto:fxsen@foxmail.com">
    **/
    private static void createServiceClass(Class model, String serviceDir,String project,String folder,String author) {
        try {
            String comment = getComment(model)+"接口";
            String date = DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss");
            StringBuffer buf = new StringBuffer();
            String className = "I" + model.getSimpleName() + "Service";
            String str = "/*\n" +
                    " * @copyright "+author+" <br/>\n" +
                    " * @date "+ date +" <br/>\n" +
                    " * @author "+author+"\n" +
                    " */\n" +
                    "package com.fxsen."+project+".core.models."+folder+".service;\n" +
                    "\n" +
                    "import com.fxsen.commons.core.base.common.service.ICommonService;\n" +
                    "import "+model.getName()+";\n" +
                    "/**\n" +
                    " * "+comment+"\n"+
                    " * @author "+author+"\n" +
                    " * @date "+ date +" \n" +
                    " */\n"+
                    "public interface "+className+" extends ICommonService<"+model.getSimpleName()+">{\n" +
                    "\n" +
                    "}";
            buf.append(str);
            File file = new File(serviceDir);
            if (!file .exists() && !file .isDirectory()){
                file.mkdirs();
            }
            File f = new File(serviceDir + "I" + model.getSimpleName() + "Service.java");
            if (!f.exists()) {
                f.createNewFile();
            }
            OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(f), StandardCharsets.UTF_8);
            BufferedWriter writer = new BufferedWriter(write);
            writer.write(buf.toString());
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
    * 创建ServiceImpl
    * @date 2022/4/26 22:18
    * @author fxsen <br/>
    * @email <a href="mailto:fxsen@foxmail.com">
    **/
    private static void createServiceImplClass(Class model, String serviceDir,String project,String folder,String author) {
        try {
            String comment = getComment(model)+"接口实现";
            String date = DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss");
            StringBuffer buf = new StringBuffer();
            String className = model.getSimpleName() + "ServiceImpl";
            String str = "/*\n" +
                    " * @copyright "+author+" <br/>\n" +
                    " * @date "+ DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss") +" <br/>\n" +
                    " * @author "+author+"\n" +
                    " */\n" +
                    "package com.fxsen."+project+".core.models."+folder+".service.impl;\n" +
                    "\n" +
                    "import org.springframework.stereotype.Service;\n" +
                    "\n" +
                    "import com.fxsen.commons.core.base.common.service.impl.CommonServiceImpl;\n" +
                    "import com.fxsen."+project+".core.models."+folder+".service.I"+model.getSimpleName()+"Service;\n" +
                    "import "+model.getName()+";\n" +
                    "/**\n" +
                    " * "+comment+"\n"+
                    " * @author "+author+"\n" +
                    " * @date "+ date +" \n" +
                    " */\n"+
                    "@Service\n" +
                    "public class "+className+" extends CommonServiceImpl<"+model.getSimpleName()+"> implements I"+model.getSimpleName()+"Service{\n" +
                    "\n" +
                    "}\n" +
                    "";
            buf.append(str);
            File file = new File(serviceDir);
            if (!file .exists() && !file .isDirectory()){
                file.mkdirs();
            }
            File f = new File(serviceDir + model.getSimpleName() + "ServiceImpl.java");
            if (!f.exists()) {
                f.createNewFile();
            }
            OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(f), StandardCharsets.UTF_8);
            BufferedWriter writer = new BufferedWriter(write);
            writer.write(buf.toString());
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



    private static String getString(String[] str, String tag) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < str.length; i++) {
            sb.append(str[i]).append(tag);
        }

        return sb.toString();
    }
    private static String getComment(Class model){
        TableComment tableComment = (TableComment)model.getAnnotation(TableComment.class);
        TableName tableName = (TableName)model.getAnnotation(TableName.class);
        return tableComment.value()+"（"+tableName.value()+"）";
    }
}
